package com.sen.design.pattern.creational.singleton;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Test {

    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 单线程使用懒汉式不会出问题
//        LazySingleton lazySingleton = LazySingleton.getInstance();
//        System.out.println("lazySingleton = " + lazySingleton);

//        // 多线程使用懒汉式
//        Thread thread = new Thread(new ThreadTest());
//        Thread thread2 = new Thread(new ThreadTest());
//        thread.start();
//        thread2.start();
        // 序列化/反序列化会破坏单例模式，在使用单例模式的时候要注意
//        HungrySingleton instance = HungrySingleton.getInstance();
//        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("singleton_file"));
//        oos.writeObject(instance);
//
//        File file = new File("singleton_file");
//        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
//        HungrySingleton o = (HungrySingleton) ois.readObject();
//        System.out.println("instance = " + instance);
//        System.out.println("o = " + o);
//        System.out.println(instance == o);

//        Class<HungrySingleton> objectClass = HungrySingleton.class;
//        Constructor<HungrySingleton> constructor = objectClass.getDeclaredConstructor();
//        constructor.setAccessible(true);
//        HungrySingleton instance = HungrySingleton.getInstance();
//        HungrySingleton newInstance = constructor.newInstance();
//        System.out.println("instance = " + instance);
//        System.out.println("newInstance = " + newInstance);
//        System.out.println(instance == newInstance);

        EnumInstance instance = EnumInstance.getInstance();
        instance.printTest();
    }
}
